package com.sksamuel.hoplite.decoder

import com.sksamuel.hoplite.ConfigFailure
import com.sksamuel.hoplite.ConfigResult
import com.sksamuel.hoplite.DecoderContext
import com.sksamuel.hoplite.Node
import com.sksamuel.hoplite.StringNode
import com.sksamuel.hoplite.fp.invalid
import com.sksamuel.hoplite.fp.valid
import java.util.Locale
import kotlin.reflect.KType

class LocaleDecoder : NullHandlingDecoder<Locale> {

  override fun supports(type: KType): Boolean = type.classifier == Locale::class

  override fun safeDecode(
    node: Node,
    type: KType,
    context: DecoderContext
  ): ConfigResult<Locale> = when (node) {
    is StringNode -> Locale.forLanguageTag(node.value).valid()
    else -> ConfigFailure.DecodeError(node, type).invalid()
  }
}
